<template>
	<view class="page-content">
		<view class="content">
			<textarea v-model="content" placeholder="请输入此刻的想法" />
			<!-- <uni-file-picker v-model="img" ref="files" @select="select"  :auto-upload="false"/> -->
			<view class="del-row-box" v-if="showImgs">
				<view class="img-box"  :style="{width:img_width + 'px',height:img_width +'px'}" v-for="(item, idx) in imgs" :key="item">
					<image :src="item" mode="aspectFill" @click="imgsPreview(idx)"></image>
					<view class="icon-del-box" @click.stop="delImg(idx)">
						<view class="icon-del"></view>
						<view class="icon-del rotate"></view>
					</view>
				</view>
				<view class="is-add" @click="chooseImg" v-if="imgs.length <= 8" :style="{width:img_width + 'px',height:img_width +'px'}">
					<view class="icon-add"></view>
					<view class="icon-add rotate"></view>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	import {
		mapGetters,
		mapActions
	} from 'vuex';
	import {
		getOssUploadsParams,
		addDynamic
	} from '@/common/api.js';
	
	export default {
		data() {
			return {
				content: '',
				imgs: [],
				showImgs: true,
				system:{
					w:0,
					h:0,
					scale:1,
					systemScale:1,
				},
			};
		},
		computed: {
			...mapGetters(['companyInfo','selIndex']),
			img_width() {
			  return (this.system.w - 46)/3;
			}
		},
		onNavigationBarButtonTap(e) {
			console.log(23, e)
			if (e.index == 0) {
				this.saved()
			}
		},
		onShow() {
			this.getSystem()
		},
		methods: {
			/**
			 * @description: 获取设备信息
			 * @param {type} 
			 * @return {type} 
			 * @author: hch
			 */
			getSystem() {
				uni.getSystemInfo().then(res =>{
					let system = res[1]
					this.system.scale = 667 / 375 //按照苹果留 375*667比例 其他型号手机等比例缩放 显示
					this.system.systemScale = system .windowWidth / 375 //按照苹果留 375*667比例 其他型号手机等比例缩放 显示
					this.system.w = system.windowWidth;
					this.system.h = system.windowHeight;
				})
				
			},
			chooseImg() {
				uni.chooseImage({
					count:9,
					sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
					sourceType: ['album', 'camera'], //从相册选择
					success: (res) => {
						console.log(JSON.stringify(res.tempFilePaths));
						this.imgs.push(...res.tempFilePaths)
					}
				});
			},
			
			imgsPreview(current) {
				uni.previewImage({
					current,
					urls: this.imgs
				});
			},
			
			delImg(idx) {
				console.log('delImg', idx);
				this.imgs.splice(idx, 1);
				this.showImgs = false
				this.$nextTick(() => {
					this.showImgs = true
				})
			},
			// 上传文件
			uploadFile(file_path, fileType, type) {
				console.log('uploadFile', file_path);
				return new Promise((resolve, reject) => {
					//let suffix = "."+filename.extname;
					let file_name = new Date().getTime() + Math.random().toString(36).substring(3, 20) + type;
					getOssUploadsParams().then(res => {
						let uploadTask = uni.uploadFile({
							url: res.data.host,
							filePath: file_path,
							fileType,
							name: 'file',
							formData: {
								name: file_path,
								'key': res.data.dir + file_name,
								'policy': res.data.policy,
								'OSSAccessKeyId': res.data.accessid,
								'success_action_status': '200',
								//让服务端返回200,不然，默认会返回204
								'signature': res.data.signature,
							},
							success: (res2) => {
								console.log('upload-res', res2)
								// _self.objdata.person.img = res.data.host + '/' + res.data.dir + file_name;
								const url = res.data.host + '/' + res.data.dir + file_name;
								resolve(url)
							},
							fail: (err) => {
								console.log('uploadImage fail', err);
								uni.showModal({
									content: err.errMsg,
									showCancel: false
								});
								reject()
							}
						});
					})
				})
			},
			async saved(){
				if (this.content === "") {
					uni.showToast({
						title: "内容不能为空！",
						icon: 'none',
						duration: 2000
					})
					return;
				}
				
				const len = this.imgs.length
				uni.showLoading({
					mask: true
				})
				const urls = []
				for (let i = 0; i < len; i++) {
					const url = await this.uploadFile(this.imgs[i], 'image', '.jpg')
					console.log('url', url);
					urls.push(url)
				}
				//const imgStr = urls.join(',')
				//console.log(444,imgStr)
				let params = {
					company_id: this.companyInfo.id,
					content: this.content,
					img: urls
				};
				addDynamic(params).then(res=>{
					uni.hideLoading()
					if(res.code === 2000){
						uni.showToast({
							icon: 'none',
							title:'发布成功'
						})
						this.$util.prePage().getDynamic();
						setTimeout(() =>{
							uni.navigateBack({
								delta:1
							})
						},1000)
					} else {
						uni.showToast({
							icon: 'none',
							title: res.msg
						})
					}
				}).catch(() => {
					uni.hideLoading()
				})
			},
			select(e) {
				console.log('选择文件：', e)
				let _self = this;
				let filename = e.tempFiles[0]
				let file_path = e.tempFilePaths[0]
				let suffix = "." + filename.extname;
				let file_name = new Date().getTime() + Math.random().toString(36).substring(3, 20) + suffix
				console.log(312, file_name, filename)
				getOssUploadsParams().then(res => {
					console.log(123, res)
					let uploadTask = uni.uploadFile({
						url: res.data.host,
						filePath: file_path,
						fileType: 'image',
						name: 'file',
						formData: {
							name: file_path,
							'key': res.data.dir + file_name,
							'policy': res.data.policy,
							'OSSAccessKeyId': res.data.accessid,
							'success_action_status': '200',
							//让服务端返回200,不然，默认会返回204
							'signature': res.data.signature,
						},
						success: (res2) => {
							console.log('uploadImage success, res is:', res2)
							// _self.img = res.data.host + '/office/' + file_name;
							let imgs = [];
							imgs = res.data.host + '/' + res.data.dir + file_name;
							_self.img.push(imgs)
							uni.showToast({
								title: '上传成功',
								icon: 'success',
								duration: 1000
							});
						},
						fail: (err) => {
							console.log('uploadImage fail', err);
							uni.showModal({
								content: err.errMsg,
								showCancel: false
							});
						}
					});
					uploadTask.onProgressUpdate((res) => {
						console.log("上传进度" + res.progress);
						this.progres = res.progress;
					});
				})
			},
		}
	}
</script>

<style lang="scss">
.page-content {
	background-color: #F8F8F8;
	width: 100%;
	height: 100%;
	.content {
		padding: 40rpx 30rpx;
		margin-top: 30rpx;
		background-color: #FFFFFF;
		.del-row-box {
			display: flex;
			flex-wrap: wrap;
			margin-bottom: 20rpx;
		
			.box-img {
				margin-right: 20rpx;
				margin-bottom: 20rpx;
				border-radius: 8rpx;
			}
		
			.icon-sc {
				display: flex;
				justify-content: center;
				align-items: center;
				background: #F8F8F8;
				border-radius: 8rpx;
			}
		
			.img-box {
				margin-bottom: 10rpx;
				margin-right: 10rpx;
				position: relative;
		
				>image {
					width: 100%;
					height: 100%;
					border-radius: 6rpx;
				}
		
				>.icon {
					position: absolute;
					top: 6rpx;
					right: 6rpx;
					z-index: 10;
				}
			}
		
			>image {
				width: 160rpx;
				height: 160rpx;
			}
		}
	}
}
.icon-del-box {
	/* #ifndef APP-NVUE */
	display: flex;
	/* #endif */
	align-items: center;
	justify-content: center;
	position: absolute;
	top: 5px;
	right: 5px;
	height: 26px;
	width: 26px;
	border-radius: 50%;
	background-color: rgba(0, 0, 0, 0.5);
	z-index: 2;
	transform: rotate(-45deg);
}					
.icon-del {
	width: 15px;
	height: 2px;
	background-color: #fff;
	border-radius: 2px;
}					
.is-add {
	/* #ifndef APP-NVUE */
	display: flex;
	/* #endif */
	width: 160rpx;
	height: 160rpx;
	align-items: center;
	justify-content: center;
	background: #f5f5f5;
}

.icon-add {
	width: 30px;
	height: 4px;
	background-color: #BBBBBB;
	border-radius: 2px;
}

.rotate {
	position: absolute;
	transform: rotate(90deg);
}
</style>
